package com.mrd.gtimp.business.action;

import com.mrd.constant.MsgConstants;
import com.mrd.evaluate.entity.Evaluation;
import com.mrd.evaluate.entity.EvaluationRecord;
import com.mrd.evaluate.service.EvaluationBiz;
import com.mrd.evaluate.service.EvaluationRecordBiz;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.gtimp.base.service.CompanyBiz;
import com.mrd.gtimp.business.entity.Declaration;
import com.mrd.gtimp.business.service.DeclarationBiz;
import com.mrd.gtimp.business.service.GtimpEvaluationBiz;
import com.mrd.util.LoginUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

/**
 * Created by lenovo on 2016/8/29.
 */
@Controller
@RequestMapping("/evaluation")
public class EvaluationAction {

    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(EvaluationAction.class);

    @Resource
    private CompanyBiz companyBiz;

    @Resource
    private EvaluationBiz evaluationBiz;

    @Resource
    private EvaluationRecordBiz evaluationRecordBiz;

    @Resource
    private DeclarationBiz declarationBiz;

    @Resource
    private GtimpEvaluationBiz gtimpEvaluationBiz;

    /**
     * 评价主页，客户
     */
    @RequestMapping("/mainCustomer")
    public String mainCustomer(Model model, Jqgrid jqgrid, String declaration_type, String supplier_com_id, String supplier_com_name) {
        String companyId = LoginUtil.getLoginUser().getCompany().getId();
        jqgrid.addRule(new SearchRule("customer.id", SearchRuleOption.eq, companyId));
        jqgrid.setSize(1);
        if (StringUtils.isNotEmpty(supplier_com_name)) {
            model.addAttribute("supplier_com_name", supplier_com_name);
        }
        if (StringUtils.isNotEmpty(declaration_type)) {
            if (declaration_type.equalsIgnoreCase("E")) {
                model.addAttribute("declaration_type_show", "出口");
            } else if (declaration_type.equalsIgnoreCase("I")) {
                model.addAttribute("declaration_type_show", "进口");
            }
            jqgrid.addRule(new SearchRule("declaration_type", SearchRuleOption.eq, declaration_type));
            model.addAttribute("declaration_type", declaration_type);
        }
        if (StringUtils.isNotEmpty(supplier_com_id)) {
            jqgrid.addRule(new SearchRule("supCompany.id", SearchRuleOption.eq, supplier_com_id));
            model.addAttribute("supplier_com_id", supplier_com_id);
        }
        Page<Declaration> declarationPage = gtimpEvaluationBiz.findDeclarationList(jqgrid);
        model.addAttribute("pageNo", jqgrid.getPage().getPageNumber() + 1);
        model.addAttribute("totalPages", declarationPage.getTotalPages());
        List<Declaration> declarationList = declarationPage.getContent();
        model.addAttribute("declarationList", declarationList);
        for (Declaration declaration : declarationList) {
            Evaluation evalution = declaration.getEvaluation();
            if (evalution != null) {
                List<EvaluationRecord> evaluationRecords = evalution.getEvaluationRecords();
                evaluationRecords.sort((o1, o2) -> {
                    if (o1 == null) {
                        return -1;
                    } else if (o2 == null) {
                        return -1;
                    } else {
                        return o1.getEvalTime().compareTo(o2.getEvalTime());
                    }
                });
                Map<String, EvaluationRecord> map = this.getEvaluationRecordMap(evaluationRecords, declaration);
                model.addAttribute(declaration.getId(), map);
            }
        }
        return "/evaluation/main_customer";
    }

    /**
     * 评价主页，供应商
     */
    @RequestMapping("/main")
    public String main(Model model, Jqgrid jqgrid, String businessId, String SNO, String declaration_type, String customer_com_id, String customer_com_name) {
        String companyId = LoginUtil.getLoginUser().getCompany().getId();
        jqgrid.addRule(new SearchRule("supCompany.id", SearchRuleOption.eq, companyId));
        jqgrid.setSize(1);
        if (StringUtils.isNotEmpty(customer_com_name)) {
            model.addAttribute("customer_com_name", customer_com_name);
        }
        if (StringUtils.isNotEmpty(businessId)) {
            jqgrid.addRule(new SearchRule("businessId", SearchRuleOption.eq, businessId));
            model.addAttribute("businessId", businessId);
        }
        if (StringUtils.isNotEmpty(SNO)) {
            jqgrid.addRule(new SearchRule("sno", SearchRuleOption.eq, SNO));
            model.addAttribute("SNO", SNO);
        }
        if (StringUtils.isNotEmpty(declaration_type)) {
            if (declaration_type.equalsIgnoreCase("E")) {
                model.addAttribute("declaration_type_show", "出口");
            } else if (declaration_type.equalsIgnoreCase("I")) {
                model.addAttribute("declaration_type_show", "进口");
            }
            jqgrid.addRule(new SearchRule("declaration_type", SearchRuleOption.eq, declaration_type));
            model.addAttribute("declaration_type", declaration_type);
        }
        if (StringUtils.isNotEmpty(customer_com_id)) {
            jqgrid.addRule(new SearchRule("customer.id", SearchRuleOption.eq, customer_com_id));
            model.addAttribute("customer_com_id", customer_com_id);
        }
        Page<Declaration> declarationPage = gtimpEvaluationBiz.findDeclarationList(jqgrid);
        model.addAttribute("totalPages", declarationPage.getTotalPages());
        List<Declaration> declarationList = declarationPage.getContent();
        model.addAttribute("declarationList", declarationList);
        for (Declaration declaration : declarationList) {
            Evaluation evalution = declaration.getEvaluation();
            if (evalution != null) {
                List<EvaluationRecord> evaluationRecords = evalution.getEvaluationRecords();
                evaluationRecords.sort((o1, o2) -> {
                    if (o1 == null) {
                        return -1;
                    } else if (o2 == null) {
                        return -1;
                    } else {
                        return o1.getEvalTime().compareTo(o2.getEvalTime());
                    }
                });
                Map<String, EvaluationRecord> map = this.getEvaluationRecordMap(evaluationRecords, declaration);
                model.addAttribute(declaration.getId(), map);
            }
        }
        return "/evaluation/main";
    }

    @RequestMapping("/view")
    public String view(Model model, String relationId, String evalId) {
        model.addAttribute("viewModel", "viewModel");
        return this.edit(model, relationId, evalId);
    }

    @RequestMapping("/edit")
    public String edit(Model model, String relationId, String evalId) {
        try {
            Evaluation evaluation = null;
            if (!StringUtils.isEmpty(relationId)) {
                Declaration declaaration = declarationBiz.findEntityById(relationId);
                if (StringUtils.isEmpty(evalId)) {
                    evaluation = evaluationBiz.findByRelationId(relationId);
                } else {
                    evaluation = evaluationBiz.findEntityById(evalId);
                }
                model.addAttribute("declaaration", declaaration);
                model.addAttribute("relationId", relationId);
            }

            if (evaluation != null) {
                Filter filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
                SearchRule rule = new SearchRule("evaluation.evalId", SearchRuleOption.eq, evaluation.getEvalId());
                filters.addRule(rule);
                Pageable page = new PageRequest(0, 15, Sort.Direction.DESC, "evalTime");
                Jqgrid jqgrid = new Jqgrid(filters, page);
                Page<EvaluationRecord> evaluationRecordPage = evaluationRecordBiz.findByJqgrid(jqgrid);
                List<EvaluationRecord> evaluationRecords = evaluationRecordPage.getContent();
                model.addAttribute("evaluationRecords", evaluationRecords);
                model.addAttribute("evaluation", evaluation);
                model.addAttribute("evalId", evaluation.getEvalId());
            }
        } catch (QueryException e) {
            e.printStackTrace();
            logger.error("EvaluationAction.edit() fail!" + e.getMessage());
        }
        return "/evaluation/edit";
    }

    private Map<String, EvaluationRecord> getEvaluationRecordMap(List<EvaluationRecord> list, Declaration declaration) {
        Map<String, EvaluationRecord> map = new HashMap<>();
        if (list != null && list.size() > 0 && declaration != null) {
            for (EvaluationRecord evaluationRecord : list) {
                if (evaluationRecord.getpEvaluationRecord() == null) {
                    map.put("0", evaluationRecord);
                } else {
                    map.put(evaluationRecord.getpEvaluationRecord().getRecordId(), evaluationRecord);
                }
            }
        }
        return map;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Result save(String relationId, String pId, String evalId,int evalScore, String evalContent) {
        String username = LoginUtil.getLoginUser().getName();
        String userId = LoginUtil.getLoginUser().getId();
        try {
            evaluationRecordBiz.saveOrupdate(relationId, pId, evalId, evalContent,evalScore, username, userId);
            return Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.newSuccessInstance(MsgConstants.SAVE_FAIL);
        }
    }
}
